<template>
  <div class="p-4">
    <el-card>
      <div class="flex justify-between items-center mb-4">
        <h2 class="text-xl font-semibold">用户管理</h2>
        <el-button type="primary" @click="showAddDialog">添加用户</el-button>
      </div>
      <el-table :data="tableData" border>
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="role" label="角色"></el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button size="small" @click="editUser(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteUser(row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          class="mt-4"
          v-model:current-page="pagination.current"
          :page-size="pagination.size"
          :total="pagination.total"
          @current-change="fetchData"
      />
    </el-card>

    <!-- 添加/编辑用户对话框 -->
    <UserDialog
        v-model="dialogVisible"
        :user="currentUser"
        @submit="handleSubmit"
    />
  </div>
</template>

<script setup>
import {computed, onMounted, ref} from 'vue'
import UserDialog from './UserDialog.vue'
import {ElMessage, ElMessageBox} from "element-plus";
import {useUserStore} from "@/stores/user.js";
import {useI18n} from "vue-i18n";

const {t} = useI18n()
const dialogVisible = ref(false)
const currentUser = ref(null)
const userStore = useUserStore()
const pagination = ref({
  current: 1,
  size: 10,
  total: 0
})

// 加载状态
const loading = ref(false)

// 表格数据
const tableData = computed(() => userStore.userList)

// 获取列表数据
const fetchData = async () => {
  try {
    loading.value = true
    await userStore.fetchUser({
      current: pagination.value.current,
      size: pagination.value.size,
      ...userStore.searchParams
    })
    pagination.value.total = userStore.total
  } catch (error) {
    ElMessage.error(error.message)
  } finally {
    loading.value = false
  }
}

const showAddDialog = () => {
  currentUser.value = null
  dialogVisible.value = true
}

const editUser = (user) => {
  currentUser.value = { ...user }
  dialogVisible.value = true
}

const deleteUser = (id) => {
  ElMessageBox.confirm(
      t('确定删除此用户?'),
      t('警告'),
      {confirmButtonText: t('确定'), cancelButtonText: t('取消'), type: 'warning'}
  ).then(() => {
    let res = userStore.deleteUser(id)
    if (res.code!==200) {
      ElMessage.error(t('操作失败'))
      return
    }
    ElMessage.success(t('操作成功'))
    fetchData()
  })
}

const handleSubmit = async (userData) => {
  if (userData?.id) {
    await userStore.updateUser(userData?.id, userData)
  } else {
    await userStore.createUser(userData)
  }
  ElMessage.success(userData.id ? '更新成功' : '添加成功')
  dialogVisible.value = false
  await fetchData()
}

onMounted(fetchData)
</script>